package com.xh.imageeditor.sdk;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.xh.imageeditor.sdk.core.IMGMode;
import com.xh.imageeditor.sdk.core.IMGText;
import com.xh.imageeditor.sdk.core.file.IMGAssetFileDecoder;
import com.xh.imageeditor.sdk.core.file.IMGDecoder;
import com.xh.imageeditor.sdk.core.file.IMGFileDecoder;
import com.xh.imageeditor.sdk.core.util.IMGUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * https://github.com/minetsh/Imaging
 * 基于2020/4/30版本修改
 * Created by zhuangshaobo on 2021/4/8.
 */
public class IMGEditActivity extends IMGEditBaseActivity {

    private static final int MAX_WIDTH = 1024;

    private static final int MAX_HEIGHT = 1024;

    public static final String EXTRA_IMAGE_URI = "IMAGE_URI";

    public static final String EXTRA_IMAGE_SAVE_PATH = "IMAGE_SAVE_PATH";

    public static final String RESULT_IMAGE_PATH = "IMAGE_SAVE_PATH";

    /**
     * 启动图片编辑界面
     * @param activity activity
     * @param requestCode 请求码
     * @param imageUri 待编辑图片uri
     */
    public static void startForResult(Activity activity, int requestCode, Uri imageUri) {
        startForResult(activity, requestCode, imageUri, "");
    }

    /**
     * 启动图片编辑界面
     * @param activity activity
     * @param requestCode 请求码
     * @param imagePath 待编辑图片路径
     */
    public static void startForResult(Activity activity, int requestCode, String imagePath) {
        startForResult(activity, requestCode, imagePath, "");
    }

    /**
     * 启动图片编辑界面
     * @param activity activity
     * @param requestCode 请求码
     * @param imagePath 待编辑图片路径
     * @param savePath 图片编辑后存放的目录
     */
    public static void startForResult(Activity activity, int requestCode, String imagePath, String savePath) {
        startForResult(activity, requestCode, Uri.fromFile(new File(imagePath)), savePath);
    }

    /**
     * 启动图片编辑界面
     * @param activity activity
     * @param requestCode 请求码
     * @param imageUri 待编辑图片uri
     * @param savePath 图片编辑后存放的目录
     */
    public static void startForResult(Activity activity, int requestCode, Uri imageUri, String savePath) {
        Log.d("ImageEditorSDK", "startForResult() requestCode="+requestCode+", imageUri="+imageUri+", savePath="+savePath);
        Intent intent = new Intent(activity, IMGEditActivity.class);
        intent.putExtra(IMGEditActivity.EXTRA_IMAGE_URI, imageUri);
        intent.putExtra(IMGEditActivity.EXTRA_IMAGE_SAVE_PATH, savePath);
        activity.startActivityForResult(intent, requestCode);
        activity.overridePendingTransition(0, 0);
    }

    @Override
    public void onCreated() {

    }

    @Override
    public Bitmap getBitmap() {
        Intent intent = getIntent();
        if (intent == null) {
            return null;
        }

        Uri uri = intent.getParcelableExtra(EXTRA_IMAGE_URI);
        if (uri == null) {
            Toast.makeText(this, "传递的参数(IMAGE_URI)缺少", Toast.LENGTH_LONG).show();
            return null;
        }

        IMGDecoder decoder = null;

        String path = uri.getPath();
        if (!TextUtils.isEmpty(path)) {
            switch (uri.getScheme()) {
                case "asset":
                    decoder = new IMGAssetFileDecoder(this, uri);
                    break;
//                case "file":
                default:
                    decoder = new IMGFileDecoder(this, uri);
                    break;
            }
        }

        if (decoder == null) {
            Log.e("ImageEditorSDK", "IMGEditActivity getBitmap() decoder=null");
            return null;
        }

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 1;
        options.inJustDecodeBounds = true;

        decoder.decode(options);

        if (options.outWidth > MAX_WIDTH) {
            options.inSampleSize = IMGUtils.inSampleSize(Math.round(1f * options.outWidth / MAX_WIDTH));
        }

        if (options.outHeight > MAX_HEIGHT) {
            options.inSampleSize = Math.max(options.inSampleSize,
                    IMGUtils.inSampleSize(Math.round(1f * options.outHeight / MAX_HEIGHT)));
        }

        options.inJustDecodeBounds = false;

        Bitmap bitmap = decoder.decode(options);
        if (bitmap == null) {
            Toast.makeText(this, "无法加载图片,请检查路径是否正确", Toast.LENGTH_LONG).show();
            return null;
        }

        return bitmap;
    }

    @Override
    public void onText(IMGText text) {
        mImgView.addStickerText(text);
    }

    @Override
    public void onModeClick(IMGMode mode) {
        IMGMode cm = mImgView.getMode();
        if (cm == mode) {
            mode = IMGMode.NONE;
        }
        mImgView.setMode(mode);
        updateModeUI();

        if (mode == IMGMode.CLIP) {
            setOpDisplay(OP_CLIP);
        }
    }

    @Override
    public void onUndoClick() {
        IMGMode mode = mImgView.getMode();
        /*if (mode == IMGMode.DOODLE) {
            mImgView.undoDoodle();
        } else if (mode == IMGMode.MOSAIC) {
            mImgView.undoMosaic();
        }*/
        if (mode == IMGMode.DOODLE || mode == IMGMode.MOSAIC) {
            mImgView.undoIMGPath();
        }
    }

    @Override
    public void onCancelClick() {
        finish();
    }

    @Override
    public void onDoneClick() {
        String defaultPath = getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString();
        String path = getIntent().getStringExtra(EXTRA_IMAGE_SAVE_PATH);
        if (!TextUtils.isEmpty(path)) {
            File dir = new File(path);
            if (!dir.exists() && !dir.mkdirs()) {
                path = defaultPath;
            }
        } else {
            path = defaultPath;
        }
        if (defaultPath.equals(path)) {
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }
        Bitmap bitmap = mImgView.saveBitmap();
        if (bitmap != null) {
            String imagePath = path + "/editor_export" + System.currentTimeMillis() + ".jpg";
            FileOutputStream fout = null;
            try {
                fout = new FileOutputStream(imagePath);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fout);
            } catch (FileNotFoundException e) {
                Log.e("ImageEditorSDK", "IMGEditActivity onDoneClick() FileNotFoundException:"+e.getMessage());
                e.printStackTrace();
            } finally {
                if (fout != null) {
                    try {
                        fout.close();
                    } catch (IOException e) {
                        Log.e("ImageEditorSDK", "IMGEditActivity onDoneClick() IOException:"+e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
            Intent data = new Intent();
            data.putExtra(RESULT_IMAGE_PATH, imagePath);
            setResult(RESULT_OK, data);
            finish();
        }
    }

    @Override
    public void onCancelClipClick() {
        mImgView.cancelClip();
        setOpDisplay(mImgView.getMode() == IMGMode.CLIP ? OP_CLIP : OP_NORMAL);
    }

    @Override
    public void onDoneClipClick() {
        mImgView.doClip();
        setOpDisplay(mImgView.getMode() == IMGMode.CLIP ? OP_CLIP : OP_NORMAL);
    }

    @Override
    public void onResetClipClick() {
        mImgView.resetClip();
    }

    @Override
    public void onRotateClipClick() {
        mImgView.doRotate();
    }

    @Override
    public void onColorChanged(int checkedColor) {
        mImgView.setPenColor(checkedColor);
    }
}
